/**
 *  Paginate Script
 *
 *  @author : jihuaizhi
 *  @Time   : 2010.03.22 21:08:10 CST
 *  @note   :
 */
import com.basestone.pdlmis.view.component.PaginateBarView;
import mx.controls.Alert;
import mx.controls.Button;
import mx.collections.ArrayCollection;
import mx.events.*;


private var _itemsTotal:int=0;
private var _itemsPerPage:int=1;
private var _selectedIndex:int=0;
private var _startRangeIndex:int=1;
private var _rangeCount:int=0;

private var _selectedBtn:Button;

[Bindable]
private var _pages:int;

[Bindable]
private var _btnWidth:int=40;

[Bindable]
private var arr:ArrayCollection=new ArrayCollection();

// helps fix an issue with scrollThumb jumping around
// when scrollTrack is clicked
private var scrollTrackMouseDown:Boolean=false;

private function init():void
{
    prevBtn.addEventListener(MouseEvent.CLICK, nudgeHandler);
    nextBtn.addEventListener(MouseEvent.CLICK, nudgeHandler);
    scroller.addEventListener(MouseEvent.MOUSE_UP, scrollerMouseUpHandler);
    selectedIndex=_selectedIndex;
    
    itemsPerPage=200;
    rangeCount=5;
    itemsTotal=17500;
    selectedIndex=0;
    this.addEventListener(PaginateEvent.PAGE_CHANGE,pageChangeHandler);

}

        public function selectedIndexStepperHandler(e:Event):void
        {
            selectedIndex = selectedIndexStepper.value;
        }

        private function intervalChangeHandler(e:Event):void
        {
            itemsPerPage = ListView_PageSizeCombo.value as int;            
        }

        private function pageChangeHandler(e:PaginateEvent):void
        {
            
            var page:int = e.index;
            
            var startIndex:int = (page * e.itemsPerPage) + 1;
            var endIndex:int = Math.min((startIndex + e.itemsPerPage -1), e.itemsTotal);
            
            ListView_TitleText.text = "Results: " + String(startIndex) + " - " + String(endIndex) + " of " + e.itemsTotal;
            
            selectedIndexStepper.maximum = pages-1;
            selectedIndexStepper.value = page;
            
        }


/**
 * how many list items per page
 */
public function set itemsPerPage(n:int):void
{
    if (n == itemsPerPage)
        return;
    _itemsPerPage=n;
    update();
    //trace("SET ITEMS PER PAGE");
}

public function get itemsPerPage():int
{
    return _itemsPerPage;
}

/**
 * Total amount of items to navigate
 */
public function set itemsTotal(n:int):void
{
    if (n == itemsTotal)
        return;
    _itemsTotal=n;
    update();
    //trace("SET ITEMS TOTAL");
}

public function get itemsTotal():int
{
    return _itemsTotal;
}

/**
 * The selected page index
 */
public function set selectedIndex(n:int):void
{
    n=Math.max(0, n);
    // make sure Component is initialized or it throws an error
    if (this.initialized)
    {
        // set selected button
        if (pageItemHBox.numChildren > 0)
        {
            var btn:Button=pageItemHBox.getChildAt(n) as Button;
            if (_selectedBtn != null)
                _selectedBtn.selected=false;
            _selectedBtn=btn;
            _selectedBtn.selected=true;
        }

        // if approriate center selected button
        var halfRange:int=Math.round(rangeCount / 2);
        if (n < halfRange - 1)
        {
            movePage(0);
        }
        else if (n > (arr.length - halfRange))
        {
            movePage(-(arr.length - rangeCount) * _btnWidth);
        }
        else
        {

            movePage(-Math.round((n + 1) * _btnWidth) + (halfRange * _btnWidth));
        }

        // disable/enable next/previous buttons if selectedIndex is first or last page
        prevBtn.enabled=(n == 0 || pageItemHBox.numChildren == 0) ? false : true;
        nextBtn.enabled=(n == arr.length - 1) ? false : true;

        // dispatch a PaginateEvent					
        var evt:PaginateEvent=new PaginateEvent(PaginateEvent.PAGE_CHANGE, true);
        evt.index=n;
        evt.itemsPerPage=itemsPerPage;
        evt.itemsTotal=itemsTotal;

        dispatchEvent(evt);
    }

    // store selected index
    _selectedIndex=n;

}

public function get selectedIndex():int
{
    return _selectedIndex;
}

/**
 * How many page buttons to display
 */
[Bindable]
public function set rangeCount(n:int):void
{
    _rangeCount=n;

    scroller.maxScrollPosition=pages - rangeCount;
    scroller.scrollPosition=Math.min(scroller.scrollPosition, scroller.maxScrollPosition);
    movePage(-Math.round(scroller.scrollPosition * _btnWidth));
}

public function get rangeCount():int
{
    return _rangeCount;
}

/**
 * currently read only. Maybe there's a usecase for setting pages dynamically?
 */
public function get pages():int
{
    return _pages;
}

/**
 * Called when parameters that effect number of pages are changed
 **/
private function update():void
{

    _pages=Math.ceil(itemsTotal / itemsPerPage);

    //trace("pages = " + _pages);

    var btn:Button;
    var i:int;
    if (arr.length < _pages)
    {
        //trace("ADD pages");
        for (i=arr.length; i < _pages; i++)
        {
            arr.addItem({label: String(i + 1) as String, data: i});

            btn=new Button();
            btn.width=_btnWidth;
            btn.label=String(i + 1) as String;
            btn.data=i;
            btn.addEventListener(MouseEvent.CLICK, pageClickHandler);
            btn.setStyle("paddingLeft", 0);
            btn.setStyle("paddingRight", 0);
            btn.setStyle("cornerRadius", 0);

            pageItemHBox.addChildAt(btn, i);


        }
    }
    else if (arr.length > _pages)
    {
        //trace("REMOVE pages");
        for (i=arr.length - 1; i >= _pages; i--)
        {
            arr.removeItemAt(i);

            btn=Button(pageItemHBox.removeChildAt(i)) as Button;
            btn.removeEventListener(MouseEvent.CLICK, pageClickHandler);
            btn.width=0;

        }
    }

    //trace("arr.length = " + arr.length);

    scroller.invalidateDisplayList();

    selectedIndex=Math.min(selectedIndex, arr.length - 1);

    var evt:PaginateEvent=new PaginateEvent(PaginateEvent.TOTAL_PAGES_CHANGE, true);
    evt.index=selectedIndex;
    evt.itemsPerPage=itemsPerPage;
    evt.itemsTotal=itemsTotal;

    dispatchEvent(evt);

}

/**
 * Page Click Event Handler
 */
private function pageClickHandler(evt:Event):void
{
    var btn:Button=evt.currentTarget as Button;
    selectedIndex=btn.data as int;
}

/**
 * Next/Previous Click Event Handler
 */
private function nudgeHandler(e:MouseEvent):void
{
    switch (e.target)
    {
        case prevBtn:
            if (selectedIndex > 0)
                --selectedIndex;
            break;
        case nextBtn:
            if (selectedIndex < arr.length - 1)
                ++selectedIndex;
            break;
    }

}

/**
 * Scroll Event Handler
 */
private function scrollHandler(e:ScrollEvent):void
{
    /*
       trace("Scroll position = " + e.position);
       trace("pageMove.isPlaying = " + pageMove.isPlaying);
       trace("e.delta = " + e.delta);
       trace("e.detail = " + e.detail);
     */

    // if Scroll Track is clicked, wait till mouse up event
    // else scroll Thumb gets jumpy
    if (e.detail == "pageLeft" || e.detail == "pageRight")
    {
        scrollTrackMouseDown=true;
        return;
    }
    movePage(-(e.position * _btnWidth));
}

/**
 * fixes a issues that makes the scrollThumb jump around with
 * clicking the scrollTrack
 */
private function scrollerMouseUpHandler(e:MouseEvent):void
{

    if (scrollTrackMouseDown)
    {
        scrollTrackMouseDown=false;
        movePage(-Math.round(scroller.scrollPosition * _btnWidth));
    }

}

/**
 * tween page button view
 */
private function movePage(xPos:int):void
{
    // make sure move doesn't go past max range
    var max:int=-(pageItemHBox.width - (rangeCount * _btnWidth));
    if (xPos < max)
        xPos=max;

    // make sure move doesn't go past 0
    xPos=Math.min(0, xPos);

    pageMove.end();
    pageMove.xTo=xPos;
    pageMove.play();
}